import { getToken, setToken, removeToken } from '@/utils/auth'
import { login, getInfo } from '@/api/user' // 引入登录接口
import { constantRoutes } from '@/router'
import { resetRouter } from '@/router'
const state = {
  // 从缓存中获取token
  token: getToken(),
  userInfo: {},
  routes: constantRoutes // 静态路由的数组
}
const mutations = {
  setToken(state, token) {
    state.token = token
    // 将token持久化本地
    setToken(token)
  },
  // 移除token
  removeToken(state) {
    state.token = ''
    // 移除token缓存
    removeToken()
  },
  // 设置用户信息
  setUserInfo(state, userInfo) {
    state.userInfo = userInfo
  },
  // 动态添加路由
  setRoutes(state, newRoutes) {
    state.routes = [...constantRoutes, ...newRoutes] // 静态路由 + 动态路由
  }
}
const actions = {
  // 异步登录，保存token
  async login(context, data) {
    // console.log(data)

    // 调用登录接口
    const token = await login(data)
    context.commit('setToken', token)
  },
  // 获取用户信息
  async getUserInfo(context) {
    const userInfo = await getInfo()
    context.commit('setUserInfo', userInfo)
    return userInfo
  },

  logout() {
    // 清除token
    this.commit('user/removeToken')
    // 清除用户信息
    this.commit('user/setUserInfo', {})
    // 重置路由
    resetRouter()
  }
}
const getters = {
  token: state => state.token
}
export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}

